// ==UserScript==
// @name         评论
// @namespace    hth
// @version      0.7
// @description  get aliexpress feedback
// @author       hth
// @updateURL    https://gitee.com/great-pacey/tampermonkey/raw/master/feedback.user.js
// @match        *://feedback.aliexpress.com/display/productEvaluation.*
// @require      https://code.jquery.com/jquery-3.6.0.min.js
// @connect writewords.org.uk
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_deleteValue
// @grant unsafeWindow
// @grant window.close
// @grant window.focus
// @grant GM_setClipboard
// @grant GM_xmlhttpRequest
// ==/UserScript==

(function () {
    'use strict';
    $(function () {
        let feedbackList = GM_getValue('feedbackList') || [];
        // let maxFeedback = $('.customer-reviews').text().match(/\((\d+?)\)/)[1];
        let form = $('#l-refresh-form')[0];

        function getPage(page) {
            return new Promise((resolve, reject) => {

                let formdata = new FormData(form);
                formdata.set('page', page);
                formdata.set('currentPage', page > 1 ? page - 1 : '');

                let data = [...formdata.entries()].reduce((o, [k, v]) => (o[k] = v, o), {})

                $.ajax({
                    type: form.method,
                    url: form.action,
                    data: data,
                    success: resolve,
                    error: reject
                });
            });
        }

        function parseFeedback(html) {
            // let feedbackWarp = $('.feedback-list-wrap');
            return html.find('.feedback-item').map(function () {
                let feedback = {};
                let item = $(this);

                let userName = item.find('.fb-user-info .user-name a');
                feedback.userName = userName.text().trim();
                feedback.memberDetailUrl = userName.attr('href');

                let userCountry = item.find('.fb-user-info .user-country');
                feedback.userCountry = userCountry.text().trim();

                let star = item.find('.fb-main .star-view span');
                let starMatch = star.attr('style').match(/width:\s*?(\d+?)%/);
                if (starMatch) {
                    feedback.star = Math.round(starMatch[1] / 20);
                }

                let orders = item.find('.fb-main .user-order-info > span');
                orders.each(function () {
                    let order = $(this);
                    let strs = order.text().trim().split(':');
                    feedback[strs[0].trim().replace(/\s/ig, '_').toLowerCase()] = (strs[1] || '').trim();
                });

                let buyer = item.find('.fb-main .buyer-feedback');
                let timeNew = buyer.find('.r-time-new');
                feedback.timeNew = timeNew.text().trim();
                feedback.feedback = buyer.text().replace(timeNew.text(), '').trim();

                let photos = item.find('.fb-main .pic-view-item img');
                feedback.photos = photos.map(function () {
                    return $(this).attr('src');
                }).get();

                // feedbackWarp.append(item);

                return feedback;
            }).get();
        }

        function getPageStr(page) {
            return page == 0 ? '' : '：' + page;
        }

        function loop(page, list) {
            page = page || 1;
            return getPage(page).then((val) => {
                let html = $(val.replace(/<!DOCTYPE\s.*?>/ig, '').replace(/<(\/?)(html|body|head)>/ig, '<$1div>'));

                list = (list || []).concat(parseFeedback(html));

                let paginationNext = html.find('#complex-pager .ui-pagination-next');
                if (paginationNext.length > 0) {
                    loadAll.text(`加载所有${getPageStr(list.length)}`);
                }
                if (--MAX_COUNT > 0 && paginationNext.length > 0 && !paginationNext.hasClass('.ui-pagination-disabled')) {
                    return loop(page + 1, list);
                } else {
                    return list;
                }
            })
        }

        let openNewTab = $('<button style="margin-left: 10px;">新页面打开</button>').on('click', function () {
            window.open(location.href);
        });

        let MAX_COUNT = 200000;
        function _loadAll() {
            MAX_COUNT = Number(maxCountInput.val()) || MAX_COUNT;
            // $('.feedback-list-wrap').empty();
            // $('#complex-pager').hide();
            return loop().then(function (list) {
                feedbackList = list;
                GM_setValue('feedbackList', list);
                log();
            });
        }

        function log() {
            if (feedbackList.length > 0) {
                unsafeWindow.m = feedbackList;
                console.log('feedbackList', feedbackList);
                // GM_setClipboard(JSON.stringify(feedbackList));
            }
        }

        let loadAll = $(`<button style="margin-left: 10px;">加载所有${getPageStr(feedbackList.length)}</button>`).on('click', _loadAll);

        let openWordCount = $('<button style="margin-left: 10px;">词频统计</button>').on('click', function () {
            let newWin = window.open();
            let run = function () {
                GM_xmlhttpRequest({
                    "method": "POST",
                    "url": "http://www.writewords.org.uk/word_count.asp",
                    "data": 'txt=' + feedbackList.map(v => v[wordCountKey.val()]).toString(),
                    "headers": {
                        "user-agent": navigator.userAgent,
                        "Cache-Control": "max-age=0",
                        "Content-Type": "application/x-www-form-urlencoded",
                    },
                    "onload": function (result) {
                        newWin.document.body.innerHTML = result.responseText;
                    }
                });
            };
            if (!feedbackList) {
                _loadAll().then(run);
            } else {
                run();
            }
        });

        let wordCountKey = $('<input style="margin-left: 10px; width: 100px" value="userCountry"/>');

        const maxCountInput = $('<input style="margin-left: 10px; widht: 100px; placeholder="maxCount">')

        $('.customer-reviews').append([openNewTab, loadAll, openWordCount, wordCountKey, maxCountInput]);

        log();
    });
})();